import { guid, tuid } from '@vimi/utils-tool'
import service from 'axios'

/**
 * 生成 oss key
 * @param {string} filename
 * @param {string | 0 | 1 | 2} type
 */
const createFileName = (filename, type) => {
  // 如果设置了文件名，则直接用该名字
  if (typeof type === 'string' || type === 0) {
    return filename
  }

  // 用guid或包括时间的随机数
  const filtType = /\.[^.]+$/.exec(filename)
  return `${type === 1 ? tuid() : guid()}${filtType}`
}

/**
 * OSS上传对象
 * @param {{
 *  file: File | FileList | File[],
 *  dir: string,
 *  type: string | 0 | 1 | 2, // 0用文件名 1用tuid 2用guid string当作文件名
 *  progress?: (e: any) => any
 * }} param
 */
export const uploadFile = async ({ file, dir, type = 1, progress }) => {
  const formData = new FormData()
  const isMultiple = file.length > 1

  if (isMultiple) {
    for (let i = 0; i < file.length; i++) {
      const f = file[i]
      formData.append('files', f, createFileName(f.name, type))
    }
  } else {
    formData.append('files', file, createFileName(file.name, type))
  }

  formData.append('dir', dir)
  const res = await service.post('/object-storage/upload', formData, {
    timeout: 0,
    onUploadProgress: e => {
      if (progress && e.total > 0) {
        e.percent = (e.loaded / e.total) * 100
        progress(e)
      }
    },
  })

  if (res.data && res.data.error === false) {
    return isMultiple ? res.data.result : res.data.result[0]
  } else {
    throw res.data
  }
}

/**
 * 删除文件
 * @param {string|string[]} url 文件url
 */
export const deleteFile = async url => {
  const isMultiple = Array.isArray(url)
  const urls = isMultiple ? url : [url]

  const res = await Promise.all(
    urls.map(u =>
      service({
        method: 'POST',
        url: '/object-storage/delete',
        params: {
          url: u,
        },
      })
    )
  )

  return isMultiple ? res : res[0]
}
